package com.qf.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.qf.baseservice.impl.BaseServiceImpl;
import com.qf.entity.Cart;
import com.qf.entity.Goods;
import com.qf.entity.User;
import com.qf.mapper.ICartMapper;
import com.qf.service.ICartService;
import com.qf.service.IGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author：刘亚康
 * @Date：2020/4/9
 * @QQ：50770284
 * @Phone：18235947935
 * @Desc : 购物车实现类
 **/
@Service
@Slf4j
public class CartServiceImpl extends BaseServiceImpl<Cart> implements ICartService {

    @Autowired
    private ICartMapper cartMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private IGoodsService goodsService;

    @Override
    protected BaseMapper<Cart> getBaseMapper() {
        return cartMapper;
    }

    /**
     * 添加商品进购物车
     * @param cart
     * @param user
     * @param cartToken
     * @return
     */
    @Override
    public int addGoodsToCart(Cart cart, User user, String cartToken) {
        log.info("添加商品进购物车");
        //查询该商品添加到购物车中
        Goods goods = goodsService.getById(cart.getGoodsId());

        //计算商品小计
        BigDecimal goodsPrice=goods.getGoodsPrice();
        Integer num=cart.getGoodsCount();
        BigDecimal goodsSubtotal=goodsPrice.multiply(BigDecimal.valueOf(num));
        cart.setGoodsSubtotal(goodsSubtotal);

        if (user!=null) {
            //查询有无该商品ID的购物车去重
            QueryWrapper wrapper=new QueryWrapper();
            wrapper.eq("goods_id",cart.getGoodsId());
            Cart isCart = cartMapper.selectOne(wrapper);
            if (isCart==null){//没有该商品的购物车
                log.info("用户添加购物车");
                cart.setUserId(user.getUserId());
                cartMapper.insert(cart);
                return 1;
            }else {//有该商品的购物车，增加数量，增加小计
                log.info("用户购物车中有该商品，修改该购物车");
                isCart.setGoodsCount(isCart.getGoodsCount()+cart.getGoodsCount());
                isCart.setGoodsSubtotal(isCart.getGoodsSubtotal().add(cart.getGoodsSubtotal()));
                cartMapper.updateById(isCart);
                return 1;
            }

        }else {
            log.info("token添加购物车");
            List<Cart> cartList = redisTemplate.opsForList().range(cartToken, 0, -1);
            boolean flag=false;
            Integer index=0;
            //循环集合，查找重复
            Cart cart1 = new Cart();
            for (int i = 0; i < cartList.size(); i++) {
                if (cartList.get(i).getGoodsId().equals(cart.getGoodsId())) {
                    flag=true;
                    index=i;
                    cart1=cartList.get(i);
                }
            }
            //有重复增加数量，增加小计
            if (flag){
                log.info("token购物车中有该商品，修改该购物车");
                cart1.setGoodsCount(cart1.getGoodsCount()+cart.getGoodsCount());
                cart1.setGoodsSubtotal(cart1.getGoodsSubtotal().add(cart.getGoodsSubtotal()));
                redisTemplate.opsForList().set(cartToken,index,cart1);
                return 1;
            }else {
                log.info("token添加购物车");
                redisTemplate.opsForList().rightPush(cartToken,cart);
                return 1;
            }
        }
    }

    /**
     * 获取购物车内容
     *
     * @param user
     * @param cartToken
     * @return
     */
    @Override
    public List<Cart> getCartList(User user, String cartToken) {
        List<Cart> cartList=new ArrayList<>();
        if (user!=null) {
            log.info("用户获取");
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("user_id",user.getUserId());
            cartList = cartMapper.selectList(wrapper);

        }else {
            log.info("token获取购物车内容");
            cartList= redisTemplate.opsForList().range(cartToken, 0, -1);
        }
        log.info("遍历购物车获取每个商品信息");
        //遍历购物车获取每个商品信息
        for (Cart cart : cartList) {
            Goods goods = goodsService.getById(cart.getGoodsId());
            cart.setGoods(goods);
        }

//        //去重，用set集合
//        log.info("用Set集合去重，添加商品数量以及小计");
//        Set<Integer> set=new HashSet<>();
//        Map<Integer,Cart> map=new HashMap<>();
//        for (Cart cart : cartList) {
//            if (set.add(cart.getGoodsId())) {
//                map.put(cart.getGoodsId(),cart);
//            }else {
//                Cart mapCart=map.get(cart.getGoodsId());
//                mapCart.setGoodsCount(cart.getGoodsCount()+mapCart.getGoodsCount());
//                mapCart.setGoodsSubtotal(cart.getGoodsSubtotal().add(mapCart.getGoodsSubtotal()));
//            }
//        }
//        //清空集合
//        cartList.clear();
//        log.info("清空集合，将map中的数据放到list中");
//        Set<Map.Entry<Integer, Cart>> entries = map.entrySet();
//        for (Map.Entry<Integer, Cart> entry : entries) {
//            cartList.add(entry.getValue());
//        }
        log.info("list中数据"+cartList);
        return cartList;
    }

    /**
     * 获取购物车商品的数量
     *
     * @param user
     * @param cartToken
     * @return
     */
    @Override
    public Integer getUserCartCount(User user, String cartToken) {
        log.info("获取购物车商品数量");
        Integer cartCount=0;
        if (user!=null) {
            log.info("用户获取获取购物车商品数量");
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("user_id",user.getUserId());
            cartCount = cartMapper.selectCount(wrapper);
            log.info("用户获取获取购物车商品数量为："+cartCount);
        }else {

            cartCount = redisTemplate.opsForList().range(cartToken, 0, -1).size();
            log.info("token获取购物车数量"+cartCount);
        }
        //cartCount = getCartList(user, cartToken).size();
        log.info("获取购物车商品数量"+cartCount);
        return cartCount;
    }

    /**
     * 合并购物车
     *
     * @param loginUser
     * @param cartToken
     */
    @Override
    public void mergeCart(User loginUser, String cartToken) {
        log.info("用户登陆，合并购物车");
        List<Cart> redisCartList= redisTemplate.opsForList().range(cartToken, 0, -1);
        log.info("redis中的购物车");
        redisCartList.forEach(System.out::println);
        //获取用户购物车中所有集合
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("user_id",loginUser.getUserId());
        List<Cart> userCartlist = cartMapper.selectList(wrapper);
        log.info("数据库中的购物车");
        userCartlist.forEach(System.out::println);
        //遍历两个集合，查找重复，重复修改，没有重复新增

        //有重复存入该集合中
        List<Cart> cartListRepeat=new ArrayList<>();
        List<Integer> repeatIndex=new ArrayList<>();
        for (int i = 0; i < redisCartList.size(); i++) {
            for (Cart userCart : userCartlist) {
                if (redisCartList.get(i).getGoodsId().equals(userCart.getGoodsId())) {
                    cartListRepeat.add(redisCartList.get(i));
                    repeatIndex.add(i);
                }
            }
        }
        //删除重复的
        redisCartList.removeAll(cartListRepeat);

        log.info("redis中的删除重复后的购物车");
        redisCartList.forEach(System.out::println);

        //重复的，数量价格相加
        for (Cart userCart : userCartlist) {
            for (Cart repeatCart : cartListRepeat) {
                if (userCart.getGoodsId().equals(repeatCart.getGoodsId())) {
                    log.info("重复的："+repeatCart);
                    userCart.setGoodsCount(repeatCart.getGoodsCount()+userCart.getGoodsCount());
                    userCart.setGoodsSubtotal(repeatCart.getGoodsSubtotal().add(userCart.getGoodsSubtotal()));
                    cartMapper.updateById(userCart);
                }
            }
        }
        //不重复的添加
        for (Cart cart : redisCartList) {
            log.info("没有重复的："+cart);
            cart.setUserId(loginUser.getUserId());
            cartMapper.insert(cart);
        }
        redisTemplate.delete(cartToken);
    }

    /**
     * 修改购物车中的商品
     *
     * @param cart
     * @param user
     * @param cartToken
     * @return
     */
    @Override
    public List<Cart> updateCartNum(Cart cart, User user, String cartToken) {
        log.info("修改购物车中的商品");
        Goods goods = goodsService.getById(cart.getGoodsId());
        Cart updateCart=new Cart();
        if (user!=null) {
            log.info("用户操作");
            updateCart = cartMapper.selectById(cart.getCartId());
            log.info("修改前商品的信息"+updateCart);
            updateCart.setGoodsCount(cart.getGoodsCount());
            updateCart.setGoodsSubtotal(goods.getGoodsPrice().multiply(BigDecimal.valueOf(cart.getGoodsCount())));
            log.info("修改后商品的信息"+updateCart);
            cartMapper.updateById(updateCart);
        }else {
            log.info("token操作");
            List<Cart> cartList= redisTemplate.opsForList().range(cartToken, 0, -1);
            for (int i = 0; i < cartList.size(); i++) {
                if (cartList.get(i).getCartId().equals(cart.getCartId())){
                    updateCart=cartList.get(i);
                    updateCart.setGoodsCount(cart.getGoodsCount());
                    updateCart.setGoodsSubtotal(goods.getGoodsPrice().multiply(BigDecimal.valueOf(cart.getGoodsCount())));
                    redisTemplate.opsForList().set(cartToken,i,updateCart);
                }
            }

        }
        List<Cart> cartList = getCartList(user, cartToken);

        return cartList;
    }

    /**
     * 根据id删除购物车
     * @param user
     * @param cartToken
     * @param cartId
     * @return
     */
    @Override
    public int deleteCart(User user, String cartToken,Integer cartId) {
        if (user!=null) {
            log.info("用户删除购物车");
            int i = cartMapper.deleteById(cartId);
            return i;
        }else {
            log.info("token删除购物车");
            List<Cart> cartList = redisTemplate.opsForList().range(cartToken, 0, -1);
            for (int i = 0; i < cartList.size(); i++) {
                if (cartList.get(i).getCartId().equals(cartId)) {
                    redisTemplate.opsForList().remove(cartToken,i,cartList.get(i));
                    return 1;
                }

            }
        }
        return 1;
    }

    /**
     * 根据用户id获取用户要下单的所有购物车
     *
     * @param cartIdList
     * @param user
     * @return
     */
    @Override
    public List<Cart> getCartByUserId(List<Integer> cartIdList, User user) {
        //1:获取购物车中包含集合中的所有购物车
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("user_id",user.getUserId());
        wrapper.in("cart_Id",cartIdList);
        List<Cart> cartList = cartMapper.selectList(wrapper);
        //找到购物车中的商品
        for (Cart cart : cartList) {
            cart.setGoods(goodsService.getById(cart.getGoodsId()));
        }
        log.info("获取到用户选中的购物车");
        cartList.forEach(System.out::println);
        return cartList;
    }



}
